import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import jwt from 'jsonwebtoken'
import crypto from 'crypto'

const prisma = new PrismaClient()

// 生成分享链接
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const sheetId = params.id
    const body = await request.json()
    const { isPublic, allowEdit } = body

    // 验证用户身份
    const token = request.headers.get('authorization')?.replace('Bearer ', '')
    if (!token) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'sheet_secret') as any
    const userId = decoded.userId

    // 检查用户是否有权限分享此表格
    const sheet = await prisma.sheet.findUnique({
      where: { id: sheetId },
      include: { owner: true }
    })

    if (!sheet) {
      return NextResponse.json({ error: 'Sheet not found' }, { status: 404 })
    }

    if (sheet.ownerId !== userId) {
      return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
    }

    // 生成分享token
    const shareToken = crypto.randomBytes(32).toString('hex')

    // 更新表格的分享设置
    const updatedSheet = await prisma.sheet.update({
      where: { id: sheetId },
      data: {
        shareToken,
        isPublic: isPublic || false,
        allowEdit: allowEdit || false
      }
    })

    const shareUrl = `${process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000'}/shared/${shareToken}`

    return NextResponse.json({
      success: true,
      shareUrl,
      shareToken,
      isPublic: updatedSheet.isPublic,
      allowEdit: updatedSheet.allowEdit
    })
  } catch (error) {
    console.error('Error creating share link:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// 获取分享信息
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const sheetId = params.id

    const sheet = await prisma.sheet.findUnique({
      where: { id: sheetId },
      select: {
        id: true,
        title: true,
        description: true,
        shareToken: true,
        isPublic: true,
        allowEdit: true,
        owner: {
          select: {
            name: true,
            email: true
          }
        }
      }
    })

    if (!sheet) {
      return NextResponse.json({ error: 'Sheet not found' }, { status: 404 })
    }

    if (!sheet.isPublic && !sheet.shareToken) {
      return NextResponse.json({ error: 'Sheet is not shared' }, { status: 404 })
    }

    return NextResponse.json({
      success: true,
      sheet: {
        id: sheet.id,
        title: sheet.title,
        description: sheet.description,
        isPublic: sheet.isPublic,
        allowEdit: sheet.allowEdit,
        owner: sheet.owner
      }
    })
  } catch (error) {
    console.error('Error fetching share info:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// 撤销分享
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const sheetId = params.id

    // 验证用户身份
    const token = request.headers.get('authorization')?.replace('Bearer ', '')
    if (!token) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'sheet_secret') as any
    const userId = decoded.userId

    // 检查用户是否有权限
    const sheet = await prisma.sheet.findUnique({
      where: { id: sheetId }
    })

    if (!sheet) {
      return NextResponse.json({ error: 'Sheet not found' }, { status: 404 })
    }

    if (sheet.ownerId !== userId) {
      return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
    }

    // 撤销分享
    await prisma.sheet.update({
      where: { id: sheetId },
      data: {
        shareToken: null,
        isPublic: false,
        allowEdit: false
      }
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error revoking share:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
